package br.com.puc.controllers;

import java.util.List;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.puc.models.Professor;
import br.com.puc.models.annotations.Publico;
import br.com.puc.repositories.ProfessorRepository;

@Resource
public class ProfessorController {

	private final Result result;
	private final ProfessorRepository repository;
	
	private final Validator validator;
	
	public ProfessorController(Result result, ProfessorRepository repository, 
	Validator validator) {
		this.result = result;
		this.repository = repository;
	
		this.validator = validator;
	}

	@Publico
	@Get("/professores")
	public List<Professor> index() {
		return repository.findAll();	
	}
	
	@Post("/professores")
	public void create(Professor professor) {
		validator.validate(professor);
		validator.onErrorUsePageOf(this).newProfessor();
		repository.create(professor);
		result.redirectTo(this).index();
	}
	
	@Get("/professores/new")
	public Professor newProfessor() {
		return new Professor();
	}
	
	@Put("/professores")
	public void update(Professor professor) {
		validator.validate(professor);
		validator.onErrorUsePageOf(this).edit(professor);
		repository.update(professor);
		result.redirectTo(this).index();
	}
	
	@Get("/professores/{professor.id}/edit")
	public Professor edit(Professor professor) {
		
		return repository.find(professor.getId());
	}

	@Publico
	@Get("/professores/{professor.id}")
	public Professor show(Professor professor) {
		return repository.find(professor.getId());
	}

	@Delete("/professores/{professor.id}")
	public void destroy(Professor professor) {
		repository.destroy(repository.find(professor.getId()));
		result.redirectTo(this).index();  
	}
}